package com.bdqn.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.junit.jupiter.api.Test;

public class ShiroTester {
    @Test
    public void testShiro(){

        IniRealm realm=new IniRealm("classpath:shiro.ini");
        DefaultSecurityManager securityManager=new DefaultSecurityManager();
        securityManager.setRealm(realm);
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject=SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken("admin","123456");
        try{
            subject.login(token);
        }catch (AuthenticationException e){
            System.out.println("认证异常：");
            e.printStackTrace();
        }
        System.out.println("是否通过认证："+ subject.isAuthenticated());
        System.out.println("身份信息："+ subject.getPrincipal());
    }

    @Test
    public void testShiro2(){

        IniRealm realm=new IniRealm("classpath:shiro.ini");
        DefaultSecurityManager securityManager=new DefaultSecurityManager();
        securityManager.setRealm(realm);
        SecurityUtils.setSecurityManager(securityManager);

        Subject subject=SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken("admin","123456");

        try{
            subject.login(token);
             System.out.println("是否认证通过："+subject.isAuthenticated());
            System.out.println("是否为管理员角色："+subject.hasRole("管理员"));
            System.out.println("是否操作用户查看功能："+subject.isPermitted("user:view"));
            subject.checkPermission("user:view");
        }catch (AuthenticationException e){
            System.out.println("认证异常：");
            e.printStackTrace();
        }
    }
}
